package com.ziq.zcamp.dialog.share

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import com.facebook.imagepipeline.request.ImageRequest
import com.gmlive.camp.dialog.share.SharePicCacheInterface
import com.ziq.base.extension.dp
import com.ziq.zcamp.R
import com.ziq.zcamp.api.request.common.MiniACodeParam
import com.ziq.zcamp.api.service.ApiUrlHelper
import com.ziq.zcamp.bean.product.PlaceProduct
import com.ziq.zcamp.constant.H5Url
import com.ziq.zcamp.databinding.LayoutSharePicCachePlaceProductBinding
import com.ziq.zcamp.manager.GlobalContextManager
import com.ziq.zcamp.manager.UserManager
import com.ziq.zcamp.util.ImageUtil
import com.ziq.zcamp.util.StorageUtil
import com.ziq.zcamp.util.io.IOUtils
import java.io.FileOutputStream
import java.text.DecimalFormat

class SharePicCacheLayoutProduct @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), SharePicCacheInterface {

    var binding : LayoutSharePicCachePlaceProductBinding = LayoutSharePicCachePlaceProductBinding.inflate(LayoutInflater.from(context), this, true)

    var imageList = mutableListOf<String>()
    var way = ""

    var placeProduct : PlaceProduct? = null
    val miniPagePath = "subpages/camp/commodity-detail/index"

    private val uidSuffix by lazy{
        val id = UserManager.instance.userInfo.value?.id.toString()
        if (id.isEmpty()){
            ""
        }else{
            "&shareuid=${id}"
        }
    }

    @SuppressLint("SetTextI18n")
    fun setPlaceProductData(data: PlaceProduct){
        placeProduct = data
        way = "place_product"
        binding.containerPlaceProduct.visibility = View.VISIBLE
        binding.qrCodeBottomTxt.text = "识别小程序码  阅读完整商品信息"
        if(data.goods_url_list?.isNotEmpty() == true){
            val imageUrlOne = data.goods_url_list?.get(0)?.url?:""
            ImageUtil.updateImageFromNetwork(binding.imagePlaceProductSingle, imageUrlOne, ImageRequest.CacheChoice.DEFAULT)
            imageList.add(imageUrlOne)
        }

        binding.placeProductName.text = data.name

        if((data?.price_range?.size?:0) > 0){
            val li = data?.price_range?.sortedBy { it }
            if((li?.first()?:0) == (li?.last()?:0)){
                binding.placeProductPrice.text = "${DecimalFormat("0.##").format((li?.first()?:0) / 100f)}"
            }else {
                binding.placeProductPrice.text = "${DecimalFormat("0.##").format((li?.first()?:0) / 100f)}-${DecimalFormat("0.00").format((li?.last()?:0) / 100f)}"
            }
        }else {
            binding.placeProductPrice.text = "${DecimalFormat("0.##").format((data?.price?:0) / 100f)}"
        }

        getSanCode(finish = { minCodeUrl, bitmap ->
            if(minCodeUrl.isNotEmpty()){
                imageList.add(minCodeUrl)
            }
            isScanCodeSuccess = true
        })
    }

    var isScanCodeSuccess = false
    fun getSanCode(finish: ((minCodeUrl:String, bitmap: Bitmap?) -> Unit)? = null){
        val url = ApiUrlHelper.instance.getUrl("${H5Url.PLACE_PRODUCT_DETAIL.url}?id=${placeProduct?.commodity_id?:""}${uidSuffix}")
        ShareUtil.getSanCode(MiniACodeParam().apply {
            is_hyaline = true
            page = miniPagePath
            scene = "id=${placeProduct?.commodity_id}${uidSuffix}&share_cv="
            width = 280.toString()
        }, url,  onSuccess = { minCodeUrl:String, bitmap: Bitmap->
            binding.qrCode.post {
                binding.qrCode.setImageBitmap(bitmap)
            }
            finish?.invoke(minCodeUrl, bitmap)
            if(minCodeUrl.isNotEmpty()){
                binding.qrCodeBottomTxt.text = "识别小程序码 阅读完整内容"
            } else {
                binding.qrCodeBottomTxt.text = "识别二维码 阅读完整内容"
            }
        }, onFail = {
            finish?.invoke("", null)
        })
    }


    /**
     * 图片加载完成
     */
    override fun checkPictureBitmap(action : ()->Unit){
        val length = imageList.size
        var index = -1
        fun callback(){
            index++
            if(index < length){
                val url = imageList[index]
                ImageUtil.getBitmap(0, url, 0, 0) { _, _ ->
                    callback()
                }
            } else {
                action.invoke()
            }
        }
        if(isScanCodeSuccess){
            callback()
        } else {
            getSanCode(finish = { minCodeUrl, bitmap->
                callback()
            })
        }

    }

    override fun getMiniProgramPath(): String {
        if(placeProduct != null ){
            return "/$miniPagePath?id=${placeProduct?.commodity_id}${uidSuffix}"
        }
        return "/pages/community/index"
    }

    /**
     * 完整卡片
     */
    override fun getTotalLayoutBitmap() : Bitmap?{
        return ImageUtil.convertViewToBitmap(binding.root,
            GlobalContextManager.getResources().getDimensionPixelSize(R.dimen.dimens_dip_375),
            625.dp)
    }

    /**
     * 小程序分享标题
     */
    override fun getTitleForMiniProgram() : String{
        if(placeProduct != null){
            return placeProduct?.name?:""
        }
        return ""
    }
    /**
     * 小程序分享卡片封面
     */
    override fun getCoverBitmapForMiniProgram(action : (bitmap : Bitmap?)->Unit){
        var pic = ""
        if(placeProduct != null ){
            if(placeProduct?.goods_url_list?.get(0)?.url?.isNotEmpty() == true){
                pic = placeProduct?.goods_url_list?.get(0)?.url?:""
            }
        }
        if(pic.isEmpty()){
        }
        ImageUtil.getBitmap(0, pic, 0, 0) { _, bitmap ->
            action.invoke(bitmap)
        }
    }
    /**
     * 复制链接 无
     */
    override fun getLinkTxt() : String{
        return ""
    }

    /**
     * 保存到本地
     */
    override fun onSavePicToLocal(source:String,finish:()->Unit){
        checkPictureBitmap {
            savePicToLocal(source,getTotalLayoutBitmap())
            finish()
        }
    }

    private fun savePicToLocal(source:String,bitmap : Bitmap?){
        try {
            if(bitmap != null){
                val path = StorageUtil.getPictureFileWith("camp_share_${way}_${System.currentTimeMillis()}.png")
                var fos: FileOutputStream? = null
                try {
                    fos = FileOutputStream(path)
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos)
                    fos.flush()
                } catch (e: Exception) {
                } finally {
                    IOUtils.close(fos)
                }
                if (path.exists() && path.length() > 0) {
                    ImageUtil.insertImageToAlbum(context, path.absolutePath)
                    val msg = GlobalContextManager.getString(R.string.share_save_success_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                } else {
                    val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
                    Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
                }
            }
        } catch (ignore: Exception) {
            val msg = GlobalContextManager.getString(R.string.share_save_fail_toast)
            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show()
        }
    }
}